package com.lsk.weixin.SdkRewrite.shakearound;

import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import com.jfinal.weixin.sdk.kit.ParaMap;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.jfinal.weixin.sdk.utils.RetryUtils;

import java.util.concurrent.Callable;

/**
 * Created by Administrator on 2018/9/14 0014.
 */
public class JsTicketApi {
    private static String apiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    private String appId;
    public JsTicketApi(String appId) {
        this.appId=appId;
    }
    public  JsTicket getTicket(JsApiType jsApiType,String token) {
        String appId =this.appId;
        String key = appId + ':' + jsApiType.name();
        IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
        final ParaMap pm = ParaMap.create("access_token", token).put("type", jsApiType.name());

        String jsTicketJson = accessTokenCache.get(key);

        JsTicket jsTicket = null;
        if(StrKit.notBlank(jsTicketJson)) {
            jsTicket = new JsTicket(jsTicketJson);
        }
        if(null == jsTicket || !jsTicket.isAvailable()) {
            jsTicket = (JsTicket) RetryUtils.retryOnException(3, new Callable<JsTicket>() {
                public JsTicket call() throws Exception {
                    return new JsTicket(HttpUtils.get(JsTicketApi.apiUrl, pm.getData()));
                }
            });
            if(null != jsApiType) {
                accessTokenCache.set(key, jsTicket.getCacheJson());
            }
        }
        return jsTicket;
    }

    public static enum JsApiType {
        jsapi,
        wx_card;

        private JsApiType() {
        }
    }
}
